import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager2 viewPager2;
    private TabPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 找到布局中的TabLayout和ViewPager2
        tabLayout = findViewById(R.id.tab_layout);
        viewPager2 = findViewById(R.id.view_pager2);

        // 初始化适配器
        adapter = new TabPagerAdapter(this);
        // 添加3个Fragment和对应的Tab标题
        adapter.addFragment(new BookListFragment(), "Books");
        adapter.addFragment(new WebViewFragment(), "Search");
        adapter.addFragment(new MapFragment(), "Map");

        // 给ViewPager2设置适配器
        viewPager2.setAdapter(adapter);

        // 关联TabLayout和ViewPager2（实现Tab和页面联动）
        new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
            tab.setText(adapter.getTabTitle(position));
        }).attach();
    }
}